package com.xinxing.city.recovery.net;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;


import com.xinxing.city.recovery.entitys.BaseEntity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 晶 on 2016/3/18.
 */
public class BaseTask<T> {
    private Call<BaseEntity<T>> mCall;
    private Context mContext;
    private final int SUCCESS = 0;
    private final String TAG = "response";

    public BaseTask(Context context, Call call) {
        mCall = call;
        mContext = context;
    }

    public void handleResponse(final ResponseListener listener) {
        mCall.enqueue(new Callback<BaseEntity<T>>() {
            @Override
            public void onResponse(Call<BaseEntity<T>> call, Response<BaseEntity<T>> response) {
                if (response.isSuccessful() && response.errorBody() == null) {
                    if (response.body().getCode() == SUCCESS) {

                        listener.onSuccess((T) response.body().getData());
                    } else {
                        if(mContext!=null) {
                            Toast.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                        }else{
                            Log.e(TAG,response.body().getMessage());
                        }
                        listener.onFail();
                    }
                } else {
                    Log.d(TAG, "error code:" + response.code());
                    Log.d(TAG, "error message:" + response.message());
                    listener.onFail();
                    if(mContext!=null) {
                        Toast.makeText(mContext, "网络请求返回异常！code = " + response.code() + " ,message = " + response.message(), Toast.LENGTH_LONG).show();
                    }else{
                        Log.e(TAG,"网络请求返回异常！code = " + response.code() + " ,message = " + response.message());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<T>> call, Throwable t) {
                Log.e(TAG, "error:" + t.getMessage());
                listener.onFail();
                if(mContext!=null) {
                    Toast.makeText(mContext, "网络请求出现异常！", Toast.LENGTH_LONG).show();
                }else{
                    Log.e(TAG,"网络请求出现异常！");
                }
            }
        });
    }

    public interface ResponseListener<T> {
        void onSuccess(T t);

        void onFail();
    }
}
